<?php

class Model3_Scaffold_Controller extends Model3_Controller
{
    /**
     *
     * @var Model3_Scaffold_Model
     */
    protected $_sc;
    protected $_post = null;
    protected $_id = null;

    public function preDispatch()
    {
        $this->_sc->setView($this->view);
    }

    public function addAction()
    {
        $this->view->result = null;
        if ($this->getRequest()->isPost())
        {
            $requestPost = $this->getRequest()->getPost();
            $sideServer = $this->_sc->getSideServer();
            if ($sideServer !== null)
            {
                $msgError = '';
                $newValues = $this->filterValues($msgError);
                if ($newValues === false)
                {
                    $this->view->msgError = $msgError;
                    $this->view->result = false;
                    return;
                }
            }
            if ($this->_post == null)
            {
                $this->_post = $requestPost;
            }
            else
            {
                $this->_post = array_merge($requestPost, $this->_post);
            }
            $this->_sc->saveForm($this->_post);
            $this->view->result = true;
        }
    }

    /**
     * Valida y/o sanitiza los parametros POST
     * @param string $msgError Mensaje descriptivo del error asociado a la restriccion aplicada.
     * @return array Arreglo con los valores filtrados y/o sanitizados, FALSE
     * si se encontro un error al validar/sanitizar los datos.
     */
    public function filterValues(&$msgError)
    {
        $sideServer = $this->_sc->getSideServer();
        # Parametros en mayusculas y trim
        $requestPost = $this->getRequest()->getPost(true);
        $newValues = array();
        foreach ($sideServer as $nameField => $dataField)
        {
            $value = $requestPost[$nameField];
            if (is_array($dataField) === true)
            {
                if (count($dataField) > 0)
                {
                    $first = reset($dataField);
                    if (is_array($first) === true)
                    {
                        /**
                         * SI es un arreglo significa que se definieron varios
                         * filtros para un solo campo. En este caso se procede
                         * a aplicar cada uno de los filtros al valor.
                         */
                        foreach ($dataField as $filter)
                        {
                            $newValues[$nameField] = $this->filterValue($value, $nameField, $filter, $msgError);
                            if ($newValues[$nameField] === false)
                            {
                                return false;
                            }
                        }
                    }
                    else
                    {
                        $newValues[$nameField] = $this->filterValue($value, $nameField, $dataField, $msgError);
                        if ($newValues[$nameField] === false)
                        {
                            return false;
                        }
                    }
                }
            }
        }
        return $newValues;
    }

    /**
     * Aplicamos un filtro a un valor.
     * @param mixed $value
     * @param array $dataField
     * @return mixed
     */
    private function filterValue($value, $nameField, array $dataField, &$msgError)
    {
        $result = $value;
        $msgError = '';
        if (isset($dataField['filter']) === true)
        {
            $filter = $dataField['filter'];
            $options = array();
            if (isset($dataField['options']) === true)
            {
                $options['options'] = $dataField['options'];
            }
            if (isset($dataField['flags']) === true)
            {
                $options['flags'] = $dataField['flags'];
            }
            $result = filter_var($value, $filter, $options);
            if ($result === false)
            {
                $msgError = 'Error en el campo '.$nameField.'.';
                if (isset($dataField['message']) === true)
                {
                    $msgError = $dataField['message'];
                }
            }
        }
        return $result;
    }

    public function editAction()
    {
        $this->view->result = null;
        if ($this->_id === null)
        {
            $params = $this->getRequest()->getParams();
            var_dump($params);
            if (is_array($params) && count($params) > 0)
            {
                $keys = array_keys($params);
                $this->_id = $params[$keys[0]];
            }
        }
        if ($this->_id)
        {
            $this->_sc->setCurrentId($this->_id);
            if ($this->getRequest()->isPost())
            {
                if ($this->_post == null)
                    $this->_post = $this->getRequest()->getPost();
                else
                    $this->_post = array_merge($this->getRequest()->getPost(), $this->_post);
                $this->_sc->saveForm($this->_post);
                $this->view->result = true;
            }
            return;
        }
    }

    public function deleteAction()
    {
        if ($this->_id === null)
        {
            $params = $this->getRequest()->getParams();
            if (is_array($params) && count($params) > 0)
            {
                $keys = array_keys($params);
                $this->_id = $params[$keys[0]];
            }
        }
        if ($this->_id)
        {
            $this->_sc->deleteRecord($this->_id);
            return;
        }
    }

    public function postDispatch()
    {
        $this->view->sc = $this->_sc;
    }

}